package naga.x.game.time;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import naga.x.App;
import naga.x.common.Updatable;

public class TimeUpdater implements Updatable {

	private static final TimeUpdater INSTANCE = new TimeUpdater();
	
	private Calendar cal;
	private int today;
	private long now;
	private long offset;
	private List<DayListener> dayListeners;
	
	private static final Logger LOG = LoggerFactory.getLogger(TimeUpdater.class);
	
	private TimeUpdater() {
		cal = Calendar.getInstance();
		today = (cal.get(Calendar.YEAR) << 16) | cal.get(Calendar.DAY_OF_YEAR);
		now = cal.getTimeInMillis();
		dayListeners = new LinkedList<DayListener>();
		App.getApp().getUpdater().add(this);
	}
	
	public static TimeUpdater getInstance() {
		return INSTANCE;
	}
	
	public synchronized void addDayListener(DayListener l) {
		dayListeners.add(l);
	}
	
	public synchronized void removeDayListener(DayListener l) {
		dayListeners.remove(l);
	}
	
	@Override
	public synchronized boolean update() {
		cal.setTimeInMillis(now = utc() + offset);
		int newDay = (cal.get(Calendar.YEAR) << 16) | cal.get(Calendar.DAY_OF_YEAR);
		if (newDay != today) {
			LOG.info("[DAYCHANGED]OLD[" + today + "]NEW[" + newDay + "]");
			today = newDay;
			Iterator<DayListener> itr = dayListeners.iterator();
			while (itr.hasNext()) {
				DayListener l = itr.next();
				if (!l.dayChanged()) {
					itr.remove();
				}
			}
		}
		return true;
	}
	
	public int today() {
		return today;
	}
	
	public long now() {
		return now;
	}
	
	/**
	 * 标准时间(UTC)
	 * @see System#currentTimeMillis()
	 * @return
	 */
	public long utc() {
		return System.currentTimeMillis();
	}
	
	public void setOffset(long offset) {
		this.offset = offset;
	}
	
	public void setDate(Date date) {
		offset = date.getTime() - utc();
		now = utc() + offset;
	}
	
}
